package com.sunjy.common.utils.word;


import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.*;

/**
 * Created by zhouyao on 2017/11/23.
 */
public class WordUtils {

    public static InputStream sysWordDataReturnInputStream(WordBean wordBean) throws Exception {
        ByteArrayOutputStream ostream = null;
        OutputStreamWriter osw = null;
        BufferedWriter bw = null;
        InputStream inputStream = null;
        try {
            Configuration configuration = wordBean.getConfiguration();
            Template template = configuration.getTemplate(wordBean.getTemplateName());
            ostream = new ByteArrayOutputStream();
            osw = new OutputStreamWriter(ostream);
            bw = new BufferedWriter(osw);
            template.process(wordBean.getDataMap(),bw);
            byte[] bytes = ostream.toByteArray();
            inputStream = new ByteArrayInputStream(bytes);
            bw.flush();
            return inputStream;
        } catch (Exception ex) {
            throw ex;
        } finally {
            if (bw != null) {
                try {
                    bw.close();
                } catch (IOException e) {
                }
            }
            if (osw != null) {
                try {
                    osw.close();
                } catch (IOException e) {
                }
            }
            if (ostream != null) {
                try {
                    ostream.close();
                } catch (IOException e) {
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                }
            }
        }
    }

}
